import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

import '../../../features/auth/services/auth_service.dart';
import '../models/calendar_event.dart';

/// 日历服务提供者
final calendarServiceProvider = Provider<CalendarService>((ref) {
  // 创建用于日历API的Dio实例
  final dio = Dio(BaseOptions(
    baseUrl: 'http://10.0.2.2:9092',  // 家庭日历服务的特定域名和端口
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 30),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  ));
  
  // 添加日志拦截器，方便调试
  dio.interceptors.add(LogInterceptor(
    requestBody: true,
    responseBody: true,
  ));
  
  // 获取认证服务
  final authService = ref.read(authServiceProvider);
  
  return CalendarService(dio, authService);
});

/// 日历服务类
class CalendarService {
  final Dio _dio;
  final AuthService _authService;
  final DateFormat _dateTimeFormatter = DateFormat("yyyy-MM-dd'T'HH:mm:ss");

  CalendarService(this._dio, this._authService);

  /// 获取用户所有日历事件
  Future<List<CalendarEvent>> getAllEvents() async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法获取日历事件');
        return [];
      }

      final userId = currentUser.id;
      
      // 调用后端接口获取所有日历事件
      final response = await _dio.get('/calendar/list', queryParameters: {
        'userId': userId,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          final List<dynamic> eventsData = responseData['data'];
          return eventsData.map((eventData) => _convertToCalendarEvent(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取日历事件异常: $e');
      return [];
    }
  }

  /// 获取指定日期的日历事件
  Future<List<CalendarEvent>> getEventsByDate(DateTime date) async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法获取日历事件');
        return [];
      }

      final userId = currentUser.id;
      final formattedDate = _dateTimeFormatter.format(date);
      
      // 调用后端接口获取指定日期的日历事件
      final response = await _dio.get('/calendar/list/date', queryParameters: {
        'userId': userId,
        'date': formattedDate,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          final List<dynamic> eventsData = responseData['data'];
          return eventsData.map((eventData) => _convertToCalendarEvent(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取指定日期的日历事件异常: $e');
      return [];
    }
  }

  /// 获取指定时间范围的日历事件
  Future<List<CalendarEvent>> getEventsByTimeRange(DateTime startTime, DateTime endTime) async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法获取日历事件');
        return [];
      }

      final userId = currentUser.id;
      final formattedStartTime = _dateTimeFormatter.format(startTime);
      final formattedEndTime = _dateTimeFormatter.format(endTime);
      
      // 调用后端接口获取指定时间范围的日历事件
      final response = await _dio.get('/calendar/list/time-range', queryParameters: {
        'userId': userId,
        'startTime': formattedStartTime,
        'endTime': formattedEndTime,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          final List<dynamic> eventsData = responseData['data'];
          return eventsData.map((eventData) => _convertToCalendarEvent(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取指定时间范围的日历事件异常: $e');
      return [];
    }
  }

  /// 获取指定类型的日历事件
  Future<List<CalendarEvent>> getEventsByType(CalendarEventType eventType) async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法获取日历事件');
        return [];
      }

      final userId = currentUser.id;
      final eventTypeValue = _getEventTypeValue(eventType);
      
      // 调用后端接口获取指定类型的日历事件
      final response = await _dio.get('/calendar/list/event-type', queryParameters: {
        'userId': userId,
        'eventType': eventTypeValue,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          final List<dynamic> eventsData = responseData['data'];
          return eventsData.map((eventData) => _convertToCalendarEvent(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取指定类型的日历事件异常: $e');
      return [];
    }
  }

  /// 创建日历事件
  Future<CalendarEvent?> createEvent(CalendarEvent event) async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法创建日历事件');
        return null;
      }

      final userId = currentUser.id;
      
      // 准备请求数据
      final eventData = _convertToRequestData(event, userId);
      
      // 调用后端接口创建日历事件
      final response = await _dio.post('/calendar/create', data: eventData);

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          return _convertToCalendarEvent(responseData['data']);
        }
      }
      
      return null;
    } catch (e) {
      print('创建日历事件异常: $e');
      return null;
    }
  }

  /// 更新日历事件
  Future<CalendarEvent?> updateEvent(CalendarEvent event) async {
    try {
      // 获取当前用户
      final currentUser = _authService.getCurrentUser();
      if (currentUser == null) {
        print('用户未登录，无法更新日历事件');
        return null;
      }

      final userId = currentUser.id;
      
      // 准备请求数据
      final eventData = _convertToRequestData(event, userId);
      
      // 调用后端接口更新日历事件
      final response = await _dio.post('/calendar/update', data: eventData);

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200' && responseData['data'] != null) {
          return _convertToCalendarEvent(responseData['data']);
        }
      }
      
      return null;
    } catch (e) {
      print('更新日历事件异常: $e');
      return null;
    }
  }

  /// 删除日历事件
  Future<bool> deleteEvent(String eventId) async {
    try {
      // 调用后端接口删除日历事件
      final response = await _dio.post('/calendar/delete', queryParameters: {
        'id': eventId,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData['code'] == '200') {
          return true;
        }
      }
      
      return false;
    } catch (e) {
      print('删除日历事件异常: $e');
      return false;
    }
  }

  /// 将后端返回的数据转换为日历事件对象
  CalendarEvent _convertToCalendarEvent(Map<String, dynamic> data) {
    // 解析参与者列表
    List<String> participants = [];
    if (data['participants'] != null) {
      participants = data['participants'].toString().split(',');
    } else if (data['participantList'] != null) {
      participants = List<String>.from(data['participantList']);
    }

    // 解析事件类型
    CalendarEventType eventType = CalendarEventType.other;
    if (data['eventType'] != null) {
      eventType = _getEventTypeFromValue(data['eventType']);
    }

    return CalendarEvent(
      id: data['id'].toString(),
      title: data['title'] ?? '',
      description: data['description'] ?? '',
      startTime: data['startTime'] != null 
          ? DateTime.parse(data['startTime']) 
          : DateTime.now(),
      endTime: data['endTime'] != null 
          ? DateTime.parse(data['endTime']) 
          : null,
      eventType: eventType,
      location: data['location'],
      participants: participants,
      isAllDay: data['isAllDay'] == 1,
      isRecurring: data['isRecurring'] == 1,
      recurrenceType: data['recurrenceType'],
      reminderMinutes: data['reminderMinutes'],
    );
  }

  /// 将日历事件对象转换为请求数据
  Map<String, dynamic> _convertToRequestData(CalendarEvent event, String userId) {
    return {
      'id': event.id != 'new' ? event.id : null,
      'userId': userId,
      'title': event.title,
      'description': event.description,
      'startTime': _dateTimeFormatter.format(event.startTime),
      'endTime': event.endTime != null ? _dateTimeFormatter.format(event.endTime!) : null,
      'eventType': _getEventTypeValue(event.eventType),
      'location': event.location,
      'participants': event.participants != null ? event.participants!.join(',') : null,
      'participantList': event.participants,
      'isAllDay': event.isAllDay ? 1 : 0,
      'isRecurring': event.isRecurring ? 1 : 0,
      'recurrenceType': event.recurrenceType,
      'reminderMinutes': event.reminderMinutes,
    };
  }

  /// 获取事件类型的枚举值
  int _getEventTypeValue(CalendarEventType eventType) {
    switch (eventType) {
      case CalendarEventType.birthday:
        return 0;
      case CalendarEventType.play:
        return 1;
      case CalendarEventType.medical:
        return 2;
      case CalendarEventType.anniversary:
        return 3;
      case CalendarEventType.familyGathering:
        return 4;
      case CalendarEventType.study:
        return 5;
      case CalendarEventType.other:
        return 6;
    }
  }

  /// 根据事件类型值获取事件类型枚举
  CalendarEventType _getEventTypeFromValue(int value) {
    switch (value) {
      case 0:
        return CalendarEventType.birthday;
      case 1:
        return CalendarEventType.play;
      case 2:
        return CalendarEventType.medical;
      case 3:
        return CalendarEventType.anniversary;
      case 4:
        return CalendarEventType.familyGathering;
      case 5:
        return CalendarEventType.study;
      case 6:
      default:
        return CalendarEventType.other;
    }
  }
}
